package com.chucang.shucang.auth.config;

import com.chucang.shucang.auth.support.core.ShuCangDaoAuthenticationProvider;
import com.chucang.shucang.auth.support.core.FormIdentityLoginConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

/**
 * @author flitsneak
 * @email flitsneak@gmail.com
 * @date 2022/9/15 16:53
 * @description security配置
 */
@EnableWebSecurity
public class WebSecurityConfig {

    /**
     * spring security 默认的安全策略
     *
     * @param http security注入点
     * @return SecurityFilterChain
     * @throws Exception e
     */
    @Bean
    SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeRequests(authorizeRequests -> authorizeRequests
                        .antMatchers("/token/*")
                        .permitAll()
                        .anyRequest()
                        .authenticated()
                )
                .headers()
                .frameOptions()
                .sameOrigin()// 避免iframe同源无法登录
                .and()
                .apply(new FormIdentityLoginConfigurer()); // 表单登录个性化
        //UsernamePasswordAuthenticationToken
        http.authenticationProvider(new ShuCangDaoAuthenticationProvider());
        return http.build();
    }

    /**
     * 暴露静态资源
     * https://github.com/spring-projects/spring-security/issues/10938
     *
     * @param http http
     * @return r
     * @throws Exception e
     */
    @Bean
    @Order(0)
    SecurityFilterChain resources(HttpSecurity http) throws Exception {
        http.requestMatchers(matchers -> matchers
                        .antMatchers("/actuator/**", "/css/**", "/error")
                )
                .authorizeHttpRequests(authorize -> authorize
                        .anyRequest()
                        .permitAll()
                )
                .requestCache()
                .disable()
                .securityContext()
                .disable()
                .sessionManagement()
                .disable();
        return http.build();
    }
}
